package com.doyutu.seed.utils;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

/**
 * @author DoyuTu
 * @version 0.0.1
 * spring-boot-project-seed
 * Http常用方法
 */
public class HttpUtil {

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getRequestUri(HttpServletRequest request) {
        String uri = request.getServletPath();
        String projectName = request.getContextPath();
        if (StringUtils.isNotBlank(projectName)) {
            uri = uri.replace(projectName, "/");
        }
        uri = uri.replace("../", "/");
        while (uri.contains("//")) {
            uri = uri.replace("//", "/");
        }
        return uri;
    }

}


